//
//  LgViewController.m
//  HYNetApp
//
//  Created by 秦乾龙 on 16/10/12.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "LgViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "RegistViewController.h"
#import "MissPwdViewController.h"
#import "ZYTextField.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "WBHttpRequest+WeiboUser.h"
#import "WeiboUser.h"
#import "DyShare.h"
#import "ChooseSignViewController.h"
#import "IndexViewController.h"
#import "BindingPhoneViewController.h"
#import "IndexNewViewController.h"
#import "DyShare.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define STOREAPPID   @"1149721016"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@interface LgViewController ()<UIScrollViewDelegate,UITextFieldDelegate>
@property (nonatomic,retain)UIScrollView *scrollView
;
@property (nonatomic,retain)NSMutableArray *yinDaoArray;
@property (nonatomic,retain)UIPageControl *pageControl;
@property (nonatomic,retain)UIView *view2;
@property (nonatomic,retain)NSString *userName;
@property (nonatomic,retain)NSString *pwd;
@property (nonatomic,retain)ZYTextField *userFiled;
@property (nonatomic,retain)ZYTextField *pwdFiled;
@end
@implementation LgViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:POST_THIRDLOGIN object:nil];
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.hidesBottomBarWhenPushed =YES;
    
    
    _pwdFiled.delegate =self;
    _pwdFiled.secureTextEntry = YES;
    //    YSJViewController *ysj = [[YSJViewController alloc]init];
    //    [self .navigationController pushViewController:ysj animated:YES];
    //测试代码
//    HYTabViewController *hyTabbarVC = [[HYTabViewController alloc]init];
//    
//    //    //    hyTabbarVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:hyTabbarVC animated:YES];
    //    EGOTabBarViewController *hyTabbarVC = [[EGOTabBarViewController alloc]init];
    //    hyTabbarVC.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:hyTabbarVC animated:YES];
    //检测版本号
    [self setUI];
    [self hsUpdateApp];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(thirdLogin:) name:POST_THIRDLOGIN object:nil];
}

- (void)thirdLogin:(NSNotification *)notify {
    [[NSNotificationCenter defaultCenter] postNotificationName:POST_LOGINSUC object:nil];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        self.navigationController.navigationBarHidden = NO;
        if ([[UserData userphone] isEqualToString:@""]) {
            BindingPhoneViewController  *vc1 = [[BindingPhoneViewController alloc]init];
            [self.navigationController pushViewController:vc1 animated:YES];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    });
}

- (void)setUI
{
    CGFloat spaceToTop = 468*kScale;
    CGFloat leftSpace = 48*kScale;
    CGFloat publicLogH =  420*kScale;
    CGFloat publicFieldH =  126*kScale;
    CGFloat publicH =  48*kScale;
    CGFloat eyeH =  200*kScale;

    UIImageView *phoneImage = [[UIImageView alloc]init];
    phoneImage.image = [UIImage imageNamed:@"手机"];
    phoneImage.frame = CGRectMake(leftSpace, spaceToTop, publicH, publicH);
    [self.view addSubview:phoneImage];
    
    UILabel *chinaLable = [[UILabel alloc]init];
    chinaLable.text = @"＋86";
    chinaLable.textColor = [UIColor whiteColor];
    CGSize chinaLableSize  = [chinaLable sizeThatFits:CGSizeMake(MAXFLOAT, publicH)];
    chinaLable.frame = CGRectMake(leftSpace*2+leftSpace, spaceToTop, chinaLableSize.width, publicH);
    [self.view addSubview:chinaLable];
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(leftSpace*3+leftSpace+chinaLableSize.width, spaceToTop, 3*kScale, publicH);
    lineView.backgroundColor = ZallColorFromRGB(0x8e8e8e);
    [self.view addSubview:lineView];
    _userFiled = [[ZYTextField alloc]init];
    _userFiled.frame = CGRectMake(leftSpace*4+leftSpace+chinaLableSize.width+3*kScale, spaceToTop, kScreenW, publicH);
    _userFiled.textColor = [UIColor whiteColor];
    _userFiled.placeholder = @"请输入手机号码";
    _userFiled.keyboardType = UIKeyboardTypePhonePad;
//    _userFiled.tintColor = [UIColor whiteColor];  //设置光标颜色
//    
//    //修改占位符文字颜色
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    _userFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_userFiled.placeholder attributes:attrs];
    //占位符颜色
//    [_userFiled setValue:[UIColor redColor] forKeyPath:@"placeholderLaber.textColor"];
    _userFiled.delegate =self;
    _userFiled.tag = 10;
    [self.view addSubview:_userFiled];
    UIView *lineView2 = [[UIView alloc]init];
    lineView2.frame = CGRectMake(leftSpace, spaceToTop+publicH+30*kScale, kScreenW-2*leftSpace, 1*kScale);
    lineView2.backgroundColor = ZallColorFromRGB(0x3a3a3a);
    [self.view addSubview:lineView2];
    UIImageView *lockImage = [[UIImageView alloc]init];
    lockImage.image = [UIImage imageNamed:@"锁"];
    lockImage.frame = CGRectMake(leftSpace, spaceToTop+publicH*2+30*kScale, publicH, publicH);
    [self.view addSubview:lockImage];
    
    _pwdFiled = [[ZYTextField alloc]init];
    _pwdFiled.frame = CGRectMake(3*leftSpace, spaceToTop+publicH*2+30*kScale, kScreenW-5*leftSpace-publicH, publicH);
    _pwdFiled.textColor = [UIColor whiteColor];
    _pwdFiled.placeholder = @"请输入密码";
    _pwdFiled.delegate =self;
    _pwdFiled.tag = 11;
    _pwdFiled.secureTextEntry = YES;
    _pwdFiled.keyboardType = UIKeyboardTypeASCIICapable;
    [self.view addSubview:_pwdFiled];
    UIButton *eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    eyeBtn.frame = CGRectMake(kScreenW-publicH*2-(eyeH-publicH)/2, spaceToTop+publicH*2+30*kScale-(eyeH-publicH)/2, eyeH, eyeH);
    [eyeBtn setImage:[UIImage imageNamed:@"闭眼"] forState:UIControlStateNormal];
    [eyeBtn setImage:[UIImage imageNamed:@"睁眼"] forState:UIControlStateSelected];
    [eyeBtn addTarget:self action:@selector(eyeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:eyeBtn];
    UIView *lineView3 = [[UIView alloc]init];
    lineView3.frame = CGRectMake(leftSpace, spaceToTop+publicH*3+30*kScale*2, kScreenW-2*leftSpace, 1*kScale);
    lineView3.backgroundColor = ZallColorFromRGB(0x3a3a3a);
    [self.view addSubview:lineView3];
    CGFloat loginBtnH = 120*kScale;
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(leftSpace, publicLogH+publicFieldH*2+98*kScale, kScreenW-2*leftSpace, loginBtnH);
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    loginBtn.backgroundColor = ZallColorFromRGB(0x1fa2b6);
    loginBtn.layer.cornerRadius = loginBtnH/2.0;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    CGSize registBtnSize = [registBtn sizeThatFits:CGSizeMake(MAXFLOAT, publicH)];
    registBtn.frame = CGRectMake(leftSpace, publicLogH+publicFieldH*2+98*kScale+loginBtnH+publicH, registBtnSize.width, publicH);
    registBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    registBtn.titleLabel.textColor = ZallColorFromRGB(0xb1b1b1);
    [registBtn addTarget:self action:@selector(registClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registBtn];
    UIButton *missBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [missBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    CGSize missBtnSize = [missBtn sizeThatFits:CGSizeMake(MAXFLOAT, publicH)];
    missBtn.frame = CGRectMake(kScreenW-leftSpace-missBtnSize.width, publicLogH+publicFieldH*2+98*kScale+loginBtnH+publicH, missBtnSize.width, publicH);
    missBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    missBtn.titleLabel.textColor = ZallColorFromRGB(0xb1b1b1);
    [missBtn addTarget:self action:@selector(forgetClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:missBtn];
    
    //第三方图标
    CGFloat thirdBtnH = 118*kScale;
    CGFloat thirdToLeft = 186*kScale;
    CGFloat thirdToRegisetH = 75*kScale;
    UIButton *weChatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    weChatBtn.frame = CGRectMake(thirdToLeft, publicLogH+publicFieldH*2+98*kScale+loginBtnH+publicH*2+thirdToRegisetH, thirdBtnH, thirdBtnH);
    [weChatBtn setBackgroundImage:[UIImage imageNamed:@"微信"] forState:UIControlStateNormal];
    [weChatBtn addTarget:self action:@selector(clickWx:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:weChatBtn];
    UIButton *weiboBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    weiboBtn.frame = CGRectMake(kScreenW-thirdToLeft-thirdBtnH, publicLogH+publicFieldH*2+98*kScale+loginBtnH+publicH*2+thirdToRegisetH, thirdBtnH, thirdBtnH);
    [weiboBtn setBackgroundImage:[UIImage imageNamed:@"微博"] forState:UIControlStateNormal];
    [weiboBtn addTarget:self action:@selector(clickWb:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:weiboBtn];
    
    if (![[DyShare getInstance] checkWeiXin]) {
        weChatBtn.hidden = YES;
        weiboBtn.frame = CGRectMake(kScreenW / 2 - thirdBtnH / 2, publicLogH+publicFieldH*2+98*kScale+loginBtnH+publicH*2+thirdToRegisetH, thirdBtnH, thirdBtnH);
    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@",NSStringFromRange(range));
    if (textField.tag==10)
    {
        if (textField) {
            NSString* text = textField.text;
            //删除
            if([string isEqualToString:@""]){
                
                //删除一位
                if(range.length == 1){
                    //最后一位,遇到空格则多删除一次
                    if (range.location == text.length-1 ) {
                        if ([text characterAtIndex:text.length-1] == ' ') {
                            [textField deleteBackward];
                        }
                        return YES;
                    }
                    //从中间删除
                    else{
                        NSInteger offset = range.location;
                        
                        if (range.location < text.length && [text characterAtIndex:range.location] == ' ' && [textField.selectedTextRange isEmpty]) {
                            [textField deleteBackward];
                            offset --;
                        }
                        [textField deleteBackward];
                        textField.text = [self parseString:textField.text];
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                        return NO;
                    }
                }
                else if (range.length > 1) {
                    BOOL isLast = NO;
                    //如果是从最后一位开始
                    if(range.location + range.length == textField.text.length ){
                        isLast = YES;
                    }
                    [textField deleteBackward];
                    textField.text = [self parseString:textField.text];
                    
                    NSInteger offset = range.location;
                    if (range.location == 3 || range.location  == 8) {
                        offset ++;
                    }
                    if (isLast) {
                        //光标直接在最后一位了
                    }else{
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                    }
                    
                    return NO;
                }
                
                else{
                    return YES;
                }
            }
            
            else if(string.length >0){
                
                //限制输入字符个数
                if (([self noneSpaseString:textField.text].length + string.length - range.length > 11) ) {
                    return NO;
                }
                //判断是否是纯数字(千杀的搜狗，百度输入法，数字键盘居然可以输入其他字符)
                //            if(![string isNum]){
                //                return NO;
                //            }
                [textField insertText:string];
                textField.text = [self parseString:textField.text];
                
                NSInteger offset = range.location + string.length;
                if (range.location == 3 || range.location  == 8) {
                    offset ++;
                }
                UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                return NO;
            }else{
                return YES;
            }
            
        }
    }
    if (textField.tag==11)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    return YES;
    
}

-(NSString*)noneSpaseString:(NSString*)string
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString*)parseString:(NSString*)string
{
    if (!string) {
        return nil;
    }
    NSMutableString* mStr = [NSMutableString stringWithString:[string stringByReplacingOccurrencesOfString:@" " withString:@""]];
    if (mStr.length >3) {
        [mStr insertString:@" " atIndex:3];
    }if (mStr.length > 8) {
        [mStr insertString:@" " atIndex:8];
        
    }
    
    return  mStr;
}
-(void)hsUpdateApp
{
    //2先获取当前工程项目版本号
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    //3从网络获取appStore版本号
    NSError *error;
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];
    if (response == nil) {
        return;
    }
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        return;
    }
    NSArray *array = appInfoDic[@"results"];
    NSDictionary *dic = array[0];
    NSString *appStoreVersion = dic[@"version"];
    //4当前版本号小于商店版本号,就更新
    if([currentVersion floatValue] < [appStoreVersion floatValue])
    {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本%@,是否更新?",appStoreVersion] delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"更新",nil];
//        [alert show];
    }else{
    }
    
}
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //5实现跳转到应用商店进行更新
    if(buttonIndex==1)
    {
        //6此处加入应用在app store的地址，方便用户去更新，一种实现方式如下：
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/han-yi-wang/id%@?mt=8", STOREAPPID]];
        //        https://itunes.apple.com/cn/app/han-yi-wang/id1149721016?mt=8
        
        //        https://itunes.apple.com/us/app/id%1080182980?ls=1&mt=8
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)changeView
{
    _pageControl.currentPage = _scrollView.contentOffset.x/kScreenW;
}
- (void)btnClick
{
    
}
- (void)btnClick:(UIButton*)btn
{
    
    
    [_scrollView removeFromSuperview];
    [_pageControl removeFromSuperview];
    [_view2 removeFromSuperview];
}
-( void )textFieldDidBeginEditing:(UITextField *)textField
{
    //键盘高度216
    
    //滑动效果（动画）
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@ "ResizeForKeyboard"  context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动，以使下面腾出地方用于软键盘的显示
    self.view.frame = CGRectMake(0.0f, -150.0f, self.view.frame.size.width, self.view.frame.size.height); //64-216
    
    [UIView commitAnimations];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_userFiled resignFirstResponder];
    [_pwdFiled resignFirstResponder];
    self.view.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
}
- (void)eyeBtnClick:(UIButton*)sender
{
    if (sender.selected==YES) {
        sender.selected = NO;
        _pwdFiled.secureTextEntry = YES;
    }
    else
    {
        sender.selected = YES;
        _pwdFiled.secureTextEntry = NO;
    }
}
- (IBAction)forgetClick:(id)sender
{
    MissPwdViewController *misPwdVC = [[MissPwdViewController alloc]init];
    [self.navigationController pushViewController:misPwdVC animated:YES];
}

- (IBAction)registClick:(id)sender
{
    RegistViewController *registVC = [[RegistViewController alloc]init];
//    [self presentViewController:registVC animated:NO completion:^(){}];
    [self.navigationController pushViewController:registVC animated:YES];
}

- (IBAction)loginClick:(id)sender
{
    if (_userFiled.text.length ==0 || _pwdFiled.text.length == 0)
    {
        [ViewFactory showInfoMsg:@"请输入用户名和密码!"];
    }
    else
    {
        _pwd = _pwdFiled.text;
        
        _userName  = [_userFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSLog(@"11111%@",_pwd);
        NSString *urlStr = [[NSString stringWithFormat:@"%@/sys/login/memberLogin?mobile_no=%@&user_pwd=%@",APIYIGOU,_userName,_pwd]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        DYBaseRequest *request = [DYBaseRequest new];
        request.requestUrl = urlStr;
        [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
            [UserData login:[allDic objectForKey:@"data"]];
            NSLog(@"77777%@",allDic);
//            self.navigationController.navigationBarHidden = NO;
//            [self.navigationController popViewControllerAnimated:YES];
            NSString *isJionTribe = [NSString stringWithFormat:@"%@",allDic[@"data"][@"isJoinTribe"]] ;
            if ([isJionTribe isEqualToString:@"0"]) {
                ChooseSignViewController *choseSign = [[ChooseSignViewController alloc]init];
                [self.navigationController pushViewController:choseSign animated:YES];
            }
            else
            {
                self.navigationController.navigationBarHidden = NO;
                for (UIViewController *temp in self.navigationController.viewControllers) {
                    if ([temp isKindOfClass:[IndexNewViewController class]]) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:POST_LOGINSUC object:nil];
                        [self.navigationController popToViewController:temp animated:YES];
                    }
                } ;
            }
            
            
            
        } error:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:@"用户名与密码不符"];
        } failure:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:NETWORK_ERR];
        }];
    }
}

- (IBAction)visiterLoginClick:(id)sender
{
    
//    ZYtabBarViewController *hyTabbarVC = [[ZYtabBarViewController alloc]init];
//    [self.navigationController pushViewController:hyTabbarVC animated:YES];
            
}

- (void)clickWx:(id)sender {
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo, snsapi_base";
    req.state = @"";
    req.openID = WXKEY;
    
    [WXApi sendAuthReq:req
        viewController:self
              delegate:nil];

}

- (void)clickWb:(id)sender {
    [[DyShare getInstance] loginWeiBoWithdelegate:nil];
}

@end
